<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>5-7 元素居中：calc</title>

  <style>
    .parent {
      width: 200px;
      height: 200px;
      background: #ccc;
    }

    .child {
      width: 100px;
      height: 100px;
      background: #e00;
    }
  </style>

</head>

<body>
  <div class="parent">
    <div class="child"></div>
  </div>

  <script>
    let HTML = document.documentElement,
      child = document.querySelector(".child"),
      parent = document.querySelector(".parent"),
      // 当前居中元素相对于进行整改操作（可视化窗口大小）
      HTMLWidth = HTML.clientWidth,
      HTMLHeight = HTML.clientHeight,
      // 当前居中元素相对于进行整改操作（某个父级元素）
      parentWidth = parent.offsetWidth,
      parentHeight = parent.offsetHeight;
    // 要居中元素本身宽高
    childWidth = child.offsetWidth,
      childHeight = child.offsetHeight;

    // 相对整个屏幕
    // child.style.position = 'absolute';
    // child.style.left = (HTMLWidth - childWidth) / 2 + 'px';
    // child.style.top = (HTMLHeight - childHeight) / 2 + 'px';

    // 相对某个定位父级元素
    parent.style.position = 'relative';
    child.style.position = 'absolute';
    child.style.left = (parentWidth - childWidth) / 2 + 'px';
    child.style.top = (parentHeight - childHeight) / 2 + 'px';
  </script>
</body>

</html>